package com.sz.service.frame;

import com.sz.bean.Page;
import com.sz.dao.frame.UserDao;
import com.sz.exception.LoginException;
import com.sz.exception.SaveException;
import com.sz.pojo.frame.User;
import com.sz.util.ToolStr;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserService extends BaseService<User> {

	@Autowired
	private HttpSession httpSession;
	@Autowired
	private UserDao userDao;

	public UserService() {
		super(User.class);
	}

	/**
	 * 登录
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public User login(String username, String password, String verification, String code) {
		if (verification == null || verification.trim().length() <= 0 || code == null) {
			throw new LoginException("请输入验证码");
		}
		if (!code.toLowerCase().equals(verification.toLowerCase())) {
			throw new LoginException("验证码输入不正确");
		}
		if (username == null || username.trim().length() <= 0 || password == null || password.trim().length() <= 0) {
			throw new LoginException("请输入用户名密码");
		}
		User user = this.findByUsername(username);
		System.out.println(user);
		if (user == null) {
			throw new LoginException("用户不存在");
		}
//		if (!user.getPassword().equals(Tool.encoderByMd5(password + user.getPwdSerial()))) {
//			throw new LoginException("密码错误");
//		}
		if (!user.getPassword().equals(ToolStr.encoderByMd5(password , user.getPwdSerial()))) {
			throw new LoginException("密码错误");
		}
		if (user.getUserStatus() == User.DISABLE || user.getUserStatus() == User.DELETE) {
			throw new LoginException("您的账户已被停用，请与管理员联系");
		}
		return user;
	}

	/**
	 * app登录
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public User login(String username, String password) {
		if (username == null || username.trim().length() <= 0 || password == null || password.trim().length() <= 0) {
			throw new LoginException("请输入用户名密码");
		}
		User user = this.findByUsername(username);
		if (user == null) {
			throw new LoginException("用户不存在");
		}
//		if (!user.getPassword().equals(Tool.encoderByMd5(password + user.getPwdSerial()))) {
//			throw new LoginException("密码错误");
//		}
		if (!user.getPassword().equals(ToolStr.encoderByMd5(password , user.getPwdSerial()))) {
			throw new LoginException("密码错误");
		}
		return user;
	}

	/**
	 * 根据username查询数据
	 * 
	 * @param username
	 * @return if = null 两种可能 1：没有该用户 2：该用户用户名重复
	 */
	public User findByUsername(String username) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username =", username);
		return this.find4ParamsUnique(params);
	}

	/**
	 * 根据department查询数据
	 * 
	 * @param department
	 *            部门id
	 * @return if = null 可能 1：该部门无用户
	 */
	public List<User> findByDepartment(Long department) {
		if (department != null) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("department.id =", department);
			return this.find4Params(params);
		} else {
			return null;
		}
	}

	/**
	 * 查询所有没有部门的用户
	 * 
	 * @return
	 */
	public List<User> findNotDepartment() {
		// Map<String, Object> params = new HashMap<String, Object>();
		// params.put("department is ", "null");
		String sql = "select * from core_user where departmentId is null and userStatus  = 0 ";
		return baseDao.find4SQL(User.class, sql, null);
	}

	/**
	 * 新增或修改用户 不能用于保存user 建议调用saveuser（）方法
	 * 
	 * @param user
	 */
	@Override
	public void save(User user) throws SaveException {
		String newPwd = user.getPassword();
		try {
			if (user.getId() == null || user.getId() <= 0) {

				Map<String, Object> params = new HashMap<String, Object>();
				params.put("username =", user.getUsername());
				List<User> userList = this.find4Params(params);
				if (userList.size() > 0) {
					throw new SaveException("用户名重复");
				}
				user.setUserStatus(User.NORMAL);
				user.setPwdSerial(RandomStringUtils.random(8, true, true));
				String pwd = ToolStr.encoderByMd5(newPwd , user.getPwdSerial());
//				String pwd = Tool.encoderByMd5(newPwd + user.getPwdSerial());
				// String pwd=new SimpleHash("MD5", newPwd, user.getPwdSerial(),
				// 1024)+"";
				user.setPassword(pwd);
				baseDao.save(user);
			} else {
				User vo = this.load(user.getId());

				if (!vo.getUsername().equals(user.getUsername())) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("username =", user.getUsername());
					List<User> userList = this.find4Params(params);
					if (userList.size() > 0) {
						throw new SaveException("用户名重复");
					}
				}
				if (user.getPassword() != null && !user.getPassword().equals("")
						&& !user.getPassword().equals(vo.getPassword())) {
					vo.copy(user);
//					String pwd = Tool.encoderByMd5(newPwd + vo.getPwdSerial());
					String pwd = ToolStr.encoderByMd5(newPwd , vo.getPwdSerial());
					// String pwd=new SimpleHash("MD5", newPwd,
					// vo.getPwdSerial(), 1024)+"";
					vo.setPassword(pwd);
				} else
					vo.copy(user);

				baseDao.update(vo);
			}

		} catch (Exception e) {
			throw new SaveException(e.getMessage());
		}
	}

	// 得到所有管理员角色的用户 code == admin

	public List<User> adminUserList() {
		String hql = "select u from User u left join u.userRoleList ur left join ur.role r where r.code = :code";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("code", "admin");
		return baseDao.find4Params(hql, params);
	}

	public List<User> find4Paramsw(String hql, Map<String, Long[]> params) {
		return userDao.find4Paramsw(hql, params);
	}

	public List<User> findUser4Ids(String uIds) {
		String hql = "select * from core_user where id in (" + uIds + ")";
		return baseDao.find4SQL(User.class, hql, null);
	}

	/**
	 * 如果不指定用户id，获取当前登陆用户；如果没有指定id也没有登陆用户，使用管理员1l
	 * 
	 * @return
	 */
	public User getUser(Long userId) {
		User user = null;
		if (userId == null || userId <= 0) {
			user = (User) httpSession.getAttribute("sessionUser");
			if (user == null) {
				userId = 1l;
			} else {
				userId = user.getId();
			}
		}
		user = this.load(userId);
		if (user == null) {
			user = this.load(1l);
		}
		return user;
	}

	public List<User> find4Page(Page page, Map<String, Object> params) {
		StringBuffer hql = new StringBuffer();
		hql.append("select u from User u where u.username like :username and u.name like :uname");
		hql.append(" ORDER BY userStatus ASC");
		return baseDao.find4Page(hql.toString(), params, page);
	}

}
